/**
 * 操作委托接取信息处理模块
 */
const Sequelize = require('sequelize')
const Op = Sequelize.Op
const sequelize = require('../db/dbconfig')
const EntrustUserAcceptinfoModel = require('../db/models/entrust_user_acceptinfo')
const EntrustsModel = require('../db/models/entrusts')
const UserModel = require('../db/models/users')
const url = require("url");
const fs = require("querystring");
const entrustsAcceptInfo = EntrustUserAcceptinfoModel(sequelize)
const entrustsModel = EntrustsModel(sequelize)
const userModel = UserModel(sequelize)
// 根据委托id和用户id检测是否已接取委托
exports.postEntIdUserIdToAccept = async (req, res) => {
  try {
    const ent_id = req.body.entId;
    const user_id = req.body.userId;
    let results = await entrustsAcceptInfo.findOne({
      where: {
        ent_id: ent_id,
        user_id: user_id,
      },
    })
    return res.myMsg(results, 200)
  } catch (e) {
    return res.myMsg(e)
  }
}

// 根据委托id，用户id，用户名添加委托接取信息
exports.postEntIdToBuy = async (req, res) => {
  console.log('req.body', req.body)

  try {
    const ent_id = JSON.parse(req.body.ent_id);
    const { userId, username } = JSON.parse(req.body.userInfo);
    // 1.1 判断是否已经被自己接取
    let is_exist1 = await entrustsAcceptInfo.findOne({
      where: {
        ent_id: ent_id,
        user_id: userId,
      },
    })
    if (is_exist1) return res.myMsg('错误! 您已接取该委托!', 400)
    // 1.2 判断是否已经被他人接取
    let is_exist2 = await entrustsAcceptInfo.findOne({
      where: {
        ent_id: ent_id,
      },
    })
    if (is_exist2) return res.myMsg('错误! 该委托已被接取!', 400)
    // 3. 根据user_id查用户credit
    let user_credit = await userModel.findOne({
      attributes: ['credit'],
      where: {
        user_id: userId,
      },
    })
    // 4. 判断用户是否有足够credit
    if (parseInt(user_credit) < 50) { return res.myMSG('接取失败! 信用点数不够', 400) }
    // 5. 返回接取结果
    let results = await entrustsAcceptInfo.create({
      user_id: userId,
      ent_id: ent_id,
      username: username
    })
    if (!results) return res.myMsg('服务器内部错误，接取失败', 500)
    return res.myMsg(results, 200)
  } catch (e) {
    return res.myMsg(e)
  }
}